package com.tiny.effects;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;

import com.tiny.core.game.Game;

/**
 * * g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, 1f));
 * 
 * @author Erick Zanardo
 * 
 */
public class FadeInOutEffect extends Effect {

    private boolean in;
    private int milis;

    private float ratePerTick;
    private float alpha;
    private AlphaComposite alphaComposite;

    public FadeInOutEffect(Game game, boolean in, int milis) {
        super(game);
        this.in = in;
        this.milis = milis;
    }

    protected void init() {
        float ticks = (game.getGameConfig().getExpectedTPS() * milis) / 1000;
        ratePerTick = 1f / ticks;
        if (in) {
            alpha = 0f;
        } else {
            alpha = 1f;
        }
        alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC, alpha);
    }

    @Override
    public void update(int currentFrame) {
        if (!finished) {
            alphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC, alpha);
            if (in) {
                alpha += ratePerTick;
                if (alpha >= 1) {
                    alpha = 1f;
                    finished = true;
                }
            } else {
                alpha -= ratePerTick;
                if (alpha <= 0) {
                    alpha = 0f;
                    finished = true;
                }
            }
        }
    }

    @Override
    public void render(Graphics2D g) {
        g.setComposite(alphaComposite);
    }
}
